#!/usr/bin/env python

import pygame, sys, math, random, time
import Numeric
import lamina

from accel import AccelControl

from vector import *

MAXRADIUS=35.0

current=None






def input(events):
	global current
	
	for event in events:
		if event.type == pygame.QUIT: 
			sys.exit(0)
		elif event.type == pygame.KEYDOWN:
			# scancode 177 = aux
			if event.key == pygame.K_ESCAPE or event.scancode==177:
				sys.exit(0)
		elif event.type == pygame.MOUSEBUTTONDOWN:
			pass
		elif event.type == pygame.MOUSEBUTTONUP:
			pass
	   

def load_sound(name):
	class NoneSound:
		def play(self): pass
	if not pygame.mixer:
		return NoneSound()
	try:
		sound = pygame.mixer.Sound(name)
	except pygame.error, message:
		print "Cannot load sound:", name
		raise SystemExit, message
	return sound


if __name__=="__main__":
	pygame.init()

	if not pygame.mixer: print 'Warning, sound disabled'

	#window = pygame.display.set_mode((480, 640))
	window = pygame.display.set_mode((480, 640), pygame.FULLSCREEN|pygame.HWSURFACE|pygame.OPENGL)
	
	#screen = pygame.display.get_surface()
	screen = lamina.LaminaScreenSurface()

	# load sound

	# creates graphics

	sys.stdout.write("Loading graphics: ")
	sys.stdout.flush()

	map=pygame.image.load("data/tube.png")

	print "Done."

	a=AccelControl()


	w=map.get_size()[0]
	h=map.get_size()[1]
	
	x=w/2
	y=h/2

	vx=vy=0
	

	if pygame.font:
		font = pygame.font.Font(None, 16)
		
	last=time.time()
	print "Map!"
	while True: 
		input(pygame.event.get())

		# input: 
 		ax,ay,az=a.read()

 		#ax=(ox-acx)/100.0
 		#ay=(oy-acy)/100.0
		
		# inverse
		#ax*=-1
		ay*=-1

		vx*=0.3
		vy*=0.3

		vx+=ax*0.05
		vy+=ay*0.05
		
		x+=vx
		y+=vy



		if x<240: x=240
		if x>w-240: x=w-240
		if y<320: y=320
		if y>h-320: y=h-320
		
		s=map.subsurface(pygame.Rect(x-240, y-320,480,640))
		screen.blit(s,(0,0))		

		screen.display()
		pygame.display.flip()

		# dump debug things

		now=time.time()
		
		sys.stdout.write("\r% 5.2f, % 5.2f, % 2.2f"%(ax,ay, (1.0/(now-last))))
		last=now

		sys.stdout.flush()


